<script lang="ts" setup>
import { ref, watchEffect } from 'vue';

import { storeToRefs } from '@vben/stores';

import {
  Form,
  FormItem,
  Input,
  message,
  Select,
  Space,
  Spin,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import { propertySelect } from '#/api/iot/alarm/config';
import { sendProperty } from '#/api/iot/device/simulator';
import { thingModelSeverList } from '#/api/iot/product/thingModel';
import { useMqttStore } from '#/store/mqtt';

const useMqtt = useMqttStore();
const { mqttOption } = storeToRefs(useMqtt);

watchEffect(async () => {
  if (mqttOption.value.productId) {
    await getThingModelSelect(mqttOption.value.productId as string);
    formState.value.deviceId = mqttOption.value.deviceId;
  }
});
const spinning = ref(false);
const formState: any = ref({
  deviceId: '',
  blockId: undefined,
  itemParams: [],
});

const severOptions = ref<{ blockName: string; id: string }[]>([]); // 服务数据
const propertyOption = ref<{ id: number; identifier: string; name: string }[]>(
  [],
); // 属性下拉

// 获取服务数据下拉数据源
async function getThingModelSelect(id: string) {
  const res = await thingModelSeverList(id);
  severOptions.value = res;
}

// 获取属性下拉数据源
async function getPropertySelect(id: number) {
  spinning.value = true;
  const res = await propertySelect(id);
  propertyOption.value = res;
  formState.value.itemParams = [];
  propertyOption.value.forEach((item) => {
    formState.value.itemParams.push({
      itemId: item.id,
      value: '',
    });
  });

  spinning.value = false;
}
// 服务下拉事件
async function handleModelChange(option: any) {
  await getPropertySelect(option.id);
  formState.value.blockId = option.id;
}

function checkProperties(): boolean {
  return formState.value.itemParams.every(
    (item: { value: string }) => item.value === '',
  );
}

function onSubmit() {
  if (checkProperties()) {
    message.warning('请填写属性内容');
  } else {
    publish(formState.value);
  }
}

function onReset() {
  if (formState.value.itemParams.length > 0) {
    formState.value.itemParams.forEach((item: { value: string }) => {
      item.value = '';
    });
  }
}

//  MQTT 传值
async function publish(data: any) {
  console.log(data, 6666);

  await sendProperty(data);

  useMqtt.setMqttTable({
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    type: '云端下行',
    content: `Content:${JSON.stringify(formState.value)}`,
  });
}
</script>
<template>
  <div>
    <Form :model="formState" layout="vertical">
      <FormItem>
        <Select
          v-model:value="formState.blockId"
          placeholder="请选择模块"
          :options="severOptions"
          :field-names="{
            label: 'blockName',
            value: 'id',
            options: 'severOptions',
          }"
          @change="(_, option) => handleModelChange(option)"
        />
      </FormItem>
      <Spin :spinning="spinning" style="width: 100%">
        <FormItem
          v-for="(item, index) in propertyOption"
          :key="item.id"
          :label="item.name"
        >
          <Input
            v-model:value="formState.itemParams[index].value"
            placeholder="请输入值"
          />
        </FormItem>
      </Spin>
      <FormItem :wrapper-col="{ span: 24, offset: 0 }">
        <Space>
          <a-button
            type="primary"
            @click="onSubmit"
            :disabled="!formState.blockId"
          >
            发送指令
          </a-button>
          <a-button :disabled="!formState.blockId" @click="onReset">
            重置属性
          </a-button>
        </Space>
      </FormItem>
    </Form>
  </div>
</template>
<style scoped lang="scss"></style>
